package com.baijiayun.liveuibase.devicetesting

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothProfile
import android.content.Context
import android.media.AudioManager
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.baijiahulian.common.networkv2.*
import com.baijiayun.livecore.network.LPWebServer
import com.baijiayun.livecore.network.request.DownLoadManager
import com.baijiayun.livecore.utils.LPJsonUtils
import java.io.File
import java.math.BigDecimal


class DeviceTestingViewModel : ViewModel() {
    private val baseUrl = "http://www.baijiayun.com"

    private lateinit var context: Context
    private lateinit var webServer: LPWebServer
    private lateinit var downloadManager: DownLoadManager

    val uploadSpeed by lazy {
        MutableLiveData<Float>()
    }

    val downloadSpeed by lazy {
        MutableLiveData<Float>()
    }

    private val testStep by lazy {
        MutableLiveData<TestStep>()
    }

    val netState by lazy {
        MutableLiveData<NetState>()
    }

    val netIp by lazy {
        MutableLiveData<String>()
    }

    val earphoneState by lazy {
        MutableLiveData<Boolean>()
    }

    var netResult = true
    var cameraResult = true
    var speakerResult = true
    var micResult = true

    var netType = ""

    var isRepeatCheck = false

    fun setContext(context: Context) {
        this.context = context
        webServer = LPWebServer.getNewInstance(context, baseUrl, "")
        downloadManager = DownLoadManager.getInstance(context)
    }

    fun setTestStep(step: TestStep) {
        testStep.value = step
    }

    fun getTestStepChange(): MutableLiveData<TestStep> {
        return testStep
    }

    fun uploadNetTest(filePath: String) {
        val startTime = System.currentTimeMillis()
        webServer.testUploadNetSpeed(filePath, object : BJProgressCallback() {
            override fun onFailure(p0: HttpException?) {
                // do nothing
            }

            override fun onResponse(p0: BJResponse?) {
                val endTime = System.currentTimeMillis()
                uploadSpeed.postValue(getSpeed(startTime, endTime, 10))
                val data = LPJsonUtils.toJsonObject(p0?.responseString)
                netIp.postValue(data.get("data").asString)
            }

            override fun onProgress(p0: Long, p1: Long) {
                // do nothing
            }

        })
    }

    fun downloadTest(filePath: String) {
        val file = File(filePath)
        if (file.exists()) {
            file.delete()
        }
        file.createNewFile()
        val url = "$baseUrl/appapi/detection/download?size=${25 * 1024 * 1024}"
        val startTime = System.currentTimeMillis()
        DownLoadManager.getInstance(context).downloadFile(url, file, object : BJDownloadCallback() {
            override fun onFailure(p0: HttpException?) {
                // do nothing
            }

            override fun onProgress(p0: Long, p1: Long) {
                // do nothing
            }

            override fun onDownloadFinish(p0: BJResponse?, p1: File?) {
                val endTime = System.currentTimeMillis()
                downloadSpeed.postValue(getSpeed(startTime, endTime, 25))
            }

        })
    }

    private fun getSpeed(startTime: Long, endTime: Long, size: Int): Float {
        val sumTime = (endTime - startTime) / 1000
        val total = size * 1024 * 1024 * 8
        val speed = total / sumTime / 1000000
        var bigDecimal = BigDecimal(speed)
        return bigDecimal.setScale(2).toFloat()
    }

    fun getEarphoneStatus(context: Context) {
        val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
        if (audioManager.isWiredHeadsetOn) {
            earphoneState.value = true
        }
        val bluetoothAdapter: BluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if (bluetoothAdapter.isEnabled) {
            val a2dp: Int = bluetoothAdapter.getProfileConnectionState(BluetoothProfile.A2DP)
            val headset: Int = bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET)
            val health: Int = bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEALTH)

            // 查看是否蓝牙是否连接到三种设备的一种，以此来判断是否处于连接状态还是打开并没有连接的状态
            var flag = -1
            when {
                a2dp == BluetoothProfile.STATE_CONNECTED -> {
                    flag = a2dp
                }
                headset == BluetoothProfile.STATE_CONNECTED -> {
                    flag = headset
                }
                health == BluetoothProfile.STATE_CONNECTED -> {
                    flag = health
                }
            }
            if (flag != -1) {
                earphoneState.value = true
            }
        }
        earphoneState.value = false
    }


    enum class TestStep {
        Start,
        TestNet,
        TestCamera,
        TestSpeaker,
        TestMic,
        TestEnd
    }

    enum class NetState {
        None,
        Wifi,
        Mobile
    }
}